import React, { useState, useEffect } from 'react';
import { View, Text,Image } from '@tarojs/components';
import {Badge} from '@nutui/nutui-react-taro';
import './index.scss';

interface TabItem {
  title: string;
  icon: any; // 支持 emoji / 图片 / JSX
  activeIcon?: any;
  path?: string;
  badge?: string | number;
  dot?: boolean;
  disabled?: boolean;
}

interface EnhancedTabBarProps {
  current?: number;
  onChange?: (index: number, tab: TabItem) => void;
  hide?: boolean;
  className?: string;
  theme?: 'default' | 'custom';
  showCenterButton?: boolean;
  onCenterButtonClick?: () => void;
  tabList?: TabItem[];
}

const CustomTabBar: React.FC<EnhancedTabBarProps> = (props) => {
  const {
    current = 0,
    onChange,
    hide = false,
    className = '',
    theme = 'default',
    showCenterButton = false,
    onCenterButtonClick,
    tabList: customTabList,
  } = props;

  const defaultTabList: TabItem[] = customTabList || [];

  const [activeIndex, setActiveIndex] = useState<number>(current);

  useEffect(() => {
    setActiveIndex(current);
  }, [current]);

  const handleChange = (index: number) => {
    const tab = defaultTabList[index];
    if (!tab) return;
    if (tab.disabled) return;
    setActiveIndex(index);
    if(onChange){
      onChange(index, tab);
    }
  };

  if (hide) return null;

  return (
    <View className={`enhanced-tabbar ${className} theme-${theme}`}>
      <View className="tabbar-content">
        {defaultTabList.map((tab, index) => {
          const isActive = activeIndex === index;
          const isCenter = showCenterButton && index === Math.floor(defaultTabList.length / 2);

          return (
            <View
              key={index}
              className={`tabbar-item ${isActive ? 'active' : ''} ${tab.disabled ? 'disabled' : ''} ${isCenter ? 'center-button' : ''}`}
              onClick={() => {
                if (isCenter && onCenterButtonClick) {
                  onCenterButtonClick();
                } else {
                  handleChange(index);
                }
              }}
            >
              <View className="tabbar-icon" style={{ position: 'relative' }}>
                {/*/!* icon 可以是字符串 emoji，也可以是 JSX（例如 <Image />） *!/*/}
                {/*{isActive && tab.activeIcon ? tab.activeIcon : tab.icon}*/}
                {/*{tab.badge !== undefined && tab.badge !== null && (*/}
                {/*  <Badge value={tab.badge} className="tabbar-badge" />*/}
                {/*)}*/}
                {/*{tab.dot && <Badge dot className="tabbar-badge" />}*/}

                <Image
                  className="tabbar-icon"
                  src={isActive && tab.activeIcon ? tab.activeIcon : tab.icon}
                  mode="aspectFit"
                />
              </View>
              <Text className="tabbar-text">{tab.title}</Text>
            </View>
          );
        })}
      </View>
    </View>
  );
};

export default CustomTabBar;
